/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.aspect.advisor;

import com.hyts.aspect.AspectProxy;
import com.hyts.aspect.annotation.Log;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.implementation.bytecode.assign.Assigner;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.logging.Logger;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.aspect.advisor
 * @author:LiBo/Alex
 * @create-date:2020-04-26 17:08
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
public class MethodAdvice {

    private static Logger logger = Logger.getLogger(MethodAdvice.class.getName());

    /**
     * 方法进入操作
     * @param method
     * @param arguments
     */
    @Advice.OnMethodEnter
    public static void onMethodEnter(@Advice.Origin Method method, @Advice.AllArguments Object[] arguments) {
        if (method.getAnnotation(Log.class) != null) {
            System.out.println("Enter " + method.getName() + " with arguments: " + Arrays.toString(arguments));
        }
    }

    /**
     * 方法退出操作
     */
    @Advice.OnMethodExit
    public static void onMethodExit(
            //@Advice.Enter long startTime,
                                    @Advice.AllArguments Object[] arguments,
                                    @Advice.Return(typing= Assigner.Typing.DYNAMIC) Object result,
                                    @Advice.Origin Method method
                                   ){
        if (method.getAnnotation(Log.class) != null) {
            System.out.println("Exit " + method.getName() + " with arguments: " + Arrays.toString(arguments) + " return: " + result);
        }
    }

    /**
     * 方法推出异常
     * @param method
     * @param throwable
     */
    //@Advice.OnMethodExit
    public static void onMethodThrow(@Advice.Origin Method method,@Advice.Thrown Object throwable) {
        if (method.getAnnotation(Log.class) != null) {
            System.out.println("Exit " + method.getName() );
        }
        //System.out.println(""+throwable.getMessage());
        logger.severe("出现错误："+throwable);
    }


}
